package com.comecrd.controller;

import com.comecrd.model.Comment;
import com.comecrd.model.dto.CheckInDTO;
import com.comecrd.model.dto.CommentDTO;
import com.comecrd.service.CheckInService;
import com.comecrd.service.CommentService;
import com.comecrd.service.UserService;
import com.comecrd.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/comment")
public class CommentController {
    
    @Autowired
    private CommentService commentService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CheckInService checkInService;
    
    @Autowired
    private JWTUtil jwtUtil;
    
    // 添加评论
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addComment(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {
        
        Long checkInId = Long.valueOf(request.get("checkInId").toString());
        String content = (String) request.get("content");
        
        // 从token中获取openId
        String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
        
        // 查找用户
        com.comecrd.model.User user = userService.findByOpenId(openId);
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 检查打卡记录是否存在 - 使用DTO进行验证
        CheckInDTO checkInDTO = checkInService.findById(checkInId, user.getId());
        if (checkInDTO == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "打卡记录不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 创建评论
        Comment comment = new Comment();
        // 使用userId替代user对象
        comment.setUserId(user.getId());
        // 使用checkInId替代checkIn对象
        comment.setCheckInId(checkInDTO.getId());
        comment.setContent(content);
        
        comment = commentService.save(comment);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("comment", commentService.convertToDTO(comment));
        
        return ResponseEntity.ok(response);
    }
    
    // 获取评论列表
    @GetMapping("/list/{checkInId}")
    public ResponseEntity<Map<String, Object>> getCommentList(
            @PathVariable Long checkInId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        // 查询评论列表
        List<CommentDTO> commentDTOs = commentService.findByCheckInId(checkInId, page + 1, size);
        
        // 统计评论总数
        int total = commentService.countByCheckInId(checkInId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("list", commentDTOs);
        response.put("page", page);
        response.put("size", size);
        response.put("total", total);
        
        return ResponseEntity.ok(response);
    }
    
    // 删除评论
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Map<String, Object>> deleteComment(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {
        
        // 从token中获取openId
        String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
        
        // 查找用户
        com.comecrd.model.User user = userService.findByOpenId(openId);
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        try {
            // 删除评论
            commentService.deleteById(id, user.getId());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除失败，无权删除此评论");
            return ResponseEntity.badRequest().body(response);
        }
    }
}